// index.js
const app = getApp()
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    motto: 'Hello World',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    banners: [],
    currentDate: '',
    dailyFortune: {
      career: 0,
      wealth: 0,
      love: 0,
      health: 0
    }
  },

  onLoad() {
    this.setCurrentDate()
    this.getBanners()
    this.getDailyFortune()
  },

  onShow() {
    try {
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
          selected: 0
        })
      }
    } catch (error) {
      console.error('设置 TabBar 选中状态失败:', error)
    }
  },

  setCurrentDate() {
    try {
      const date = new Date()
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      this.setData({
        currentDate: `${year}年${month}月${day}日`
      })
    } catch (error) {
      console.error('设置日期失败:', error)
    }
  },

  getBanners() {
    try {
      // 这里应该调用实际的API获取数据
      const mockBanners = [
        { id: 1, imageUrl: '/assets/images/banner1.jpg' },
        { id: 2, imageUrl: '/assets/images/banner2.jpg' },
        { id: 3, imageUrl: '/assets/images/banner3.jpg' },
        { id: 4, imageUrl: '/assets/images/banner1.jpg' }
      ]
      this.setData({
        banners: mockBanners
      })
    } catch (error) {
      console.error('获取轮播图失败:', error)
      wx.showToast({
        title: '获取轮播图失败',
        icon: 'none'
      })
    }
  },

  getDailyFortune() {
    try {
      // 这里应该调用实际的API获取数据
      const mockFortune = {
        career: 4,
        wealth: 3,
        love: 5,
        health: 4
      }
      this.setData({
        dailyFortune: mockFortune
      })
    } catch (error) {
      console.error('获取运势失败:', error)
      wx.showToast({
        title: '获取运势失败',
        icon: 'none'
      })
    }
  },

  onBannerTap(e) {
    const id = e.currentTarget.dataset.id
    // 根据banner id跳转到对应页面
    const bannerMap = {
      1: '/pages/bazi/bazi',
      2: '/pages/ziwei/ziwei',
      3: '/pages/wuxing/wuxing',
      4: '/pages/yijing/yijing'
    }
    const url = bannerMap[id]
    if (url) {
      this.navigateTo(url)
    }
  },

  checkBirthInfo() {
    const birthInfo = wx.getStorageSync('birthInfo')
    return birthInfo ? true : false
  },

  navigateTo(url) {
    try {
      // 检查是否需要先填写出生信息
      const needsBirthInfo = [
        '/pages/bazi/bazi',
        '/pages/ziwei/ziwei',
        '/pages/wuxing/wuxing',
        '/pages/yijing/yijing'
      ]

      if (needsBirthInfo.includes(url) && !this.checkBirthInfo()) {
        // 如果需要出生信息但没有，直接跳转到出生信息页面
        wx.navigateTo({
          url: '/pages/birth-info/birth-info',
          success: () => {
            console.log('跳转到出生信息页面')
          },
          fail: (error) => {
            console.error('跳转失败:', error)
            wx.showToast({
              title: '页面跳转失败',
              icon: 'none'
            })
          }
        })
        return
      }

      // 如果不需要出生信息或已有出生信息，直接跳转到目标页面
      wx.navigateTo({
        url: url,
        success: () => {
          console.log('页面跳转成功:', url)
        },
        fail: (error) => {
          console.error('页面跳转失败:', error)
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          })
        }
      })
    } catch (error) {
      console.error('页面跳转异常:', error)
      wx.showToast({
        title: '系统异常',
        icon: 'none'
      })
    }
  },

  onGridItemTap(e) {
    const url = e.currentTarget.dataset.url
    this.navigateTo(url)
  },

  onServiceItemTap(e) {
    const url = e.currentTarget.dataset.url
    console.log('服务项点击，准备跳转到:', url)
    this.navigateTo(url)
  },

  onShareAppMessage() {
    return {
      title: '玄学命理 - 您的命理顾问',
      path: '/pages/index/index',
      imageUrl: '/assets/images/share.jpg'
    }
  },

  bindViewTap() {
    this.navigateTo('../logs/logs')
  },

  onChooseAvatar(e) {
    try {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
    } catch (error) {
      console.error('选择头像失败:', error)
    }
  },

  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },

  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
})
